package simple;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QstarzReader extends GpsReader {
	
	public QstarzReader(InputStream inputStream) {
		super(inputStream);
	}

	@Override
	public void run() {
		StringBuilder data = new StringBuilder();
		
		while(isActive())
		{
				// Remember that CR+LF is a Newline. see
				// http://en.wikipedia.org/wiki/Newline
				// CR = 13
				// LF = 10
				try {
					byte[] bytes = new byte[0];
					if (this.getInputStream().available() > 0) {
						bytes = new byte[this.getInputStream().available()];
						
						int numberRead = this.getInputStream().read(bytes);
						
						data.append(new String(bytes));

						// Uncomment the sentence below if you want "real time" GPS
						// feedback:
//						 System.out.print(new String(bytes));
					}

					// Interpret the data:
					Pattern startPattern = Pattern.compile("^(\\$)", Pattern.MULTILINE);
					Pattern endPattern = Pattern.compile("(\\*\\w{2})$", Pattern.MULTILINE);
					Matcher startMatcher = startPattern.matcher(data);

					while (startMatcher.find()) {
						Matcher endMatcher = endPattern.matcher(data);
						if (endMatcher.find(startMatcher.end())) {
							String sentence = data.subSequence(startMatcher.start(), endMatcher.end()).toString();
							data.delete(0, endMatcher.end());
							startMatcher = startPattern.matcher(data);
							
							for (IGpsListener listener : this.getGpsListeners()) {
								listener.sentenceFound(sentence);
							}
						}
					}


				} catch (IOException e) {
				}

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			
		}
	}
	
}
